<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 验证用户登录
$user = $auth->getCurrentUser();
if (!$user) {
    Response::authError('请先登录');
}

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'POST':
        if (isset($_GET['type']) && $_GET['type'] == 'avatar') {
            // 头像上传
            uploadAvatar($user['id']);
        } else {
            Response::error('无效的上传类型');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

function uploadAvatar($userId) {
    global $db;
    
    // 检查是否有文件上传
    if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
        Response::error('请选择要上传的头像文件');
    }
    
    $file = $_FILES['avatar'];
    
    // 验证文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($file['type'], $allowedTypes)) {
        Response::error('只支持 JPG、PNG、GIF、WEBP 格式的图片');
    }
    
    // 验证文件大小 (最大5MB)
    $maxSize = 5 * 1024 * 1024;
    if ($file['size'] > $maxSize) {
        Response::error('头像文件大小不能超过5MB');
    }
    
    // 创建上传目录
    $uploadDir = '../uploads/avatars/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // 生成唯一文件名
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $fileName = 'avatar_' . $userId . '_' . time() . '.' . $extension;
    $filePath = $uploadDir . $fileName;
    
    // 移动上传文件
    if (!move_uploaded_file($file['tmp_name'], $filePath)) {
        Response::error('文件上传失败');
    }
    
    // 生成访问URL
    $avatarUrl = UPLOAD_URL . 'avatars/' . $fileName;
    
    // 更新用户头像
    error_log("Updating avatar for user ID: " . $userId);
    error_log("Avatar URL: " . $avatarUrl);
    
    $result = $db->update('users', [
        'avatar' => $avatarUrl,
        'updated_at' => date('Y-m-d H:i:s')
    ], 'id = :user_id', ['user_id' => $userId]);
    
    error_log("Avatar update result: " . ($result ? 'success' : 'failed'));
    
    if ($result) {
        // 删除旧头像文件（可选）
        $oldAvatar = $db->fetchOne("SELECT avatar FROM users WHERE id = ?", [$userId]);
        if ($oldAvatar && $oldAvatar['avatar'] && strpos($oldAvatar['avatar'], UPLOAD_URL) === 0) {
            $oldFile = str_replace(UPLOAD_URL, '../uploads/', $oldAvatar['avatar']);
            if (file_exists($oldFile) && $oldFile !== $filePath) {
                unlink($oldFile);
            }
        }
        
        Response::success([
            'avatar_url' => $avatarUrl,
            'file_name' => $fileName
        ], '头像上传成功');
    } else {
        // 删除已上传的文件
        if (file_exists($filePath)) {
            unlink($filePath);
        }
        Response::error('头像更新失败');
    }
}

// 图片压缩函数（可选）
function compressImage($source, $destination, $quality = 80) {
    $info = getimagesize($source);
    
    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
    } elseif ($info['mime'] == 'image/webp') {
        $image = imagecreatefromwebp($source);
    } else {
        return false;
    }
    
    // 调整图片大小（头像建议200x200）
    $width = imagesx($image);
    $height = imagesy($image);
    $newWidth = 200;
    $newHeight = 200;
    
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    
    // 保持透明度
    if ($info['mime'] == 'image/png' || $info['mime'] == 'image/gif') {
        imagealphablending($newImage, false);
        imagesavealpha($newImage, true);
        $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
        imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
    }
    
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    // 保存压缩后的图片
    if ($info['mime'] == 'image/jpeg') {
        imagejpeg($newImage, $destination, $quality);
    } elseif ($info['mime'] == 'image/gif') {
        imagegif($newImage, $destination);
    } elseif ($info['mime'] == 'image/png') {
        imagepng($newImage, $destination, floor($quality / 10));
    } elseif ($info['mime'] == 'image/webp') {
        imagewebp($newImage, $destination, $quality);
    }
    
    imagedestroy($image);
    imagedestroy($newImage);
    
    return true;
}
?>